#coding: utf-8

from cocos2d        import *
from game.common    import *

TAG_SCROLL_LAYER    = 0x10
TAG_BATCH_SPRITE    = 0x10
TAG_FIRST_SPRITE    = 0x10
TAG_SECOND_SPRITE   = 0x11
SCENE_ROLL_SPEED    = 20.0

class ScrollScene(CCScene):
    def __init__(self, bg):
        super(ScrollScene, self).__init__()
        self.__path = bg
        self.__texW = 0
        self.__texH = 0

        scroll_layer = CCLayer()
        scroll_layer.Tag = TAG_SCROLL_LAYER
        self.addChild(scroll_layer)

        batch = CCSpriteBatchNode(self.__path)
        batch.Tag = TAG_BATCH_SPRITE
        scroll_layer.addChild(batch)

        self.__fill()

    def roll_bottom(self):
        layer = self.getChildByTag(TAG_SCROLL_LAYER)
        if not layer:
            return

        pt = CCPoint(0, layer.PositionY - self.__texH)
        ai0 = CCMoveTo(SCENE_ROLL_SPEED, pt)
        fn  = CCCallFunc(self._roll_done, self.roll_bottom)
        seq = CCSequence((ai0, fn))

        layer.runAction(seq)

    def _roll_done(self, fn):
        self.__fill()
        fn()
        print 'roll end'

    def __fill(self):
        layer = self.getChildByTag(TAG_SCROLL_LAYER)
        if not layer:
            return
        batch = layer.getChildByTag(TAG_BATCH_SPRITE)
        if not batch:
            return

        posY = 0
        spr = batch.getChildByTag(TAG_FIRST_SPRITE)
        if not spr:
            #add first sprite
            print 'add first'
            spr = CCSprite(self.__path)
            batch.addChild(spr)
            spr.Tag = TAG_FIRST_SPRITE
            spr.PositionX = spr.boundingBox.size.width / 2
            spr.PositionY = DEFAULT_GAME_HEIGHT / 2 + (spr.boundingBox.size.height - DEFAULT_GAME_HEIGHT) / 2
            self.__texW = spr.boundingBox.size.width
            self.__texH = spr.boundingBox.size.height
            posY = spr.PositionY
        else:
            batch.removeChildByTag(TAG_FIRST_SPRITE)
            spr2 = batch.getChildByTag(TAG_SECOND_SPRITE)
            spr2.Tag = TAG_FIRST_SPRITE
            posY = spr2.PositionY
            print 'posY', posY

        spr2 = CCSprite(self.__path)
        spr2.Tag = TAG_SECOND_SPRITE
        batch.addChild(spr2)
        spr2.PositionX = spr2.boundingBox.size.width / 2
        spr2.PositionY = spr2.boundingBox.size.height + posY
